import os
import time
import logging
from logging.handlers import TimedRotatingFileHandler


class Log(logging.Logger):
    
    CRITICAL = 50
    FATAL = CRITICAL
    ERROR = 40
    WARNING = 30
    WARN = WARNING
    INFO = 20
    DEBUG = 10
    NOTSET = 0
    
    def __init__(self, level=NOTSET, stream=True, file=True):
        """
        stream:是否输出到控制台
        file:是否保存到文件
        """
        self.level = level
        self.stream = stream
        self.file = file
        self.name = None
        super().__init__(self.name, level=level)
           
    def set_name(self, file_name, name=''):
        """
        file_name：保存的文件名
        name:日志名字
        """
        self.name = name
        # 设置输出格式，依次为，线程，时间，名字，信息。
        self.fmt = '%(threadName)s %(asctime)s %(name)s %(message)s '
        # 解决重复输出的问题
        if self.handlers:
            return
        else:
            if self.stream:
                self.__set_stream_handler__()
            if self.file:
                self.__set_file_handler__(file_name)
            
    def __set_file_handler__(self, file_name):
        """
        设置输出文件
        """
        logs_dir= '{}Logs'.format(file_name)
        if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            pass
        else:
            os.mkdir(logs_dir)
        # 修改log保存位置和文件名
        time_stamp = time.strftime("%Y%m%d",time.localtime())
        log_file_name ='{}.txt'.format(time_stamp + '_' + file_name)
        file_name = os.path.join(logs_dir, log_file_name)
        # 设置日志回滚, 保存在log目录, 一天保存一个文件, 保留15天
        file_handler = TimedRotatingFileHandler(filename=file_name, when='D', interval=1, backupCount=15)
        file_handler.setLevel(self.level)
        formatter = logging.Formatter(self.fmt, '%Y%m%d %H:%M:%S')
        file_handler.setFormatter(formatter)
        self.file_handler = file_handler
        self.addHandler(file_handler)

    def __set_stream_handler__(self):
        """
        设置控制台输出
        """
        stream_handler = logging.StreamHandler()
        formatter = logging.Formatter(self.fmt, '%Y-%m-%d %H:%M:%S')
        stream_handler.setFormatter(formatter)
        stream_handler.setLevel(self.level)
        self.addHandler(stream_handler)


    def resetName(self, name):
        """
        reset name
        :param name:
        :return:
        """
        self.name = name
        self.removeHandler(self.file_handler)
        self.__set_file_handler__()
        
if __name__ == '__main__' :
    my_log = Log()
    my_log.set_name('文件名', 'log名')
    my_log.info('测试log')


